package com.github.m6d21.sso.common.util;

import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *<p>
 *AES加解密
 *</p>
 *
 * @author liuyang
 * @date 2019/1/2 Wed 15:10:00
 * @since 1.0.0
 */
public class AesUtil {

    private static final Logger LOG = LoggerFactory.getLogger(AesUtil.class);

    public final static String DEFAULT_KEY = "com.github.m6d21";
    private static final String KEY_ALGORITHM = "AES";
    private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";

    public static String encrypt(String content) {
        return encrypt(DEFAULT_KEY, content);
    }

    public static String encrypt(String key, String content) {
        if (StringUtils.isEmpty(key)) {
            throw new RuntimeException("密钥不能为空");
        }
        if (StringUtils.isEmpty(content)) {
            throw new RuntimeException("加密内容不能为空");
        }
        byte[] result = new byte[0];
        try {
            Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
            byte[] byteContent = content.getBytes(StandardCharsets.UTF_8);
            cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(key));
            result = cipher.doFinal(byteContent);
        } catch (Exception e) {
            LOG.error("解密时出现异常, error:{}", e);
            throw new RuntimeException("解密时出现异常：" + content);
        }
        return Base64.encodeBase64String(result);
    }

    public static String decrypt(String content) {
        return decrypt(DEFAULT_KEY, content);
    }

    public static String decrypt(String key, String content) {
        if (StringUtils.isEmpty(key)) {
            throw new RuntimeException("密钥不能为空");
        }
        if (StringUtils.isEmpty(content)) {
            throw new RuntimeException("解密内容不能为空");
        }
        byte[] result;
        try {
            Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, getSecretKey(key));
            result = cipher.doFinal(Base64.decodeBase64(content));
        } catch (Exception e) {
            LOG.error("解密时出现异常, error:{}", e);
            throw new RuntimeException("无法对如下密文进行解密：" + content);
        }
        return new String(result, StandardCharsets.UTF_8);
    }

    private static SecretKeySpec getSecretKey(final String key) {
        try {
            KeyGenerator keyGenerator = KeyGenerator.getInstance(KEY_ALGORITHM);
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            secureRandom.setSeed(key.getBytes(StandardCharsets.UTF_8));
            //AES 要求密钥长度为 128
            keyGenerator.init(128, secureRandom);
            //生成一个密钥
            SecretKey secretKey = keyGenerator.generateKey();
            return new SecretKeySpec(secretKey.getEncoded(), KEY_ALGORITHM);
        } catch (NoSuchAlgorithmException e) {
            LOG.error("getSecretKey()时出现异常, error:{}", e);
            throw new RuntimeException("getSecretKey()时出现异常: " + e.getMessage());
        }
    }


    public static void main(String[] args) {
        String en = encrypt("hello 迷妹word!");
        System.out.println(en);
        String de = decrypt(en);
        System.out.println(de);
    }

}
